package com.lzx.iteam.util;

import android.content.Context;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import com.lzx.iteam.R;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by shijunting on 14-12-29.
 */
public class PhoneNumberArea {

    private static final String TAG = "PhoneNumberArea";

    private static Map<String,byte[]> binFileBytes = new HashMap<String, byte[]>();
    private static byte mobile_name = 0;
    private static byte union_name = 1;
    private static byte telecom_name = 2;

    private String sInternationalCode = "00";
    private String sCountryCode = "86";
    private String sISOCountryCode="CN";
    private String sCityPreCode = "0";
    private String sCountryName ="中国";
    private String mOpertatorName = null;

    public String getCountryName() {
        return sCountryName;
    }

    public String getCountryCode() {
        return sCountryCode;
    }

    public String getISOCountryCode() {
        return sISOCountryCode;
    }

    public String getCityPreCode() {
        return sCityPreCode;
    }

    public String getInternationalCode() {
        return sInternationalCode;
    }
    //定义运营商信息的数据结构
   /*static class OpPart {
        byte start;
        byte end;
        byte name_index;

        public OpPart(byte start,byte end,byte name_index) {
            this.start = start;
            this.end = end;
            this.name_index = name_index;
        }

    }*/

    // 运营商相关信息 union_name = 1  telecom_name = 2  mobile_name = 0
//  private  static  OpPart op_parts[] = {
////            new OpPart((byte) 130, (byte) 132, union_name),
////            new OpPart((byte) 133, (byte) 133, telecom_name),
////            new OpPart((byte) 134, (byte) 139, mobile_name),
////            new OpPart((byte) 144, (byte) 144, union_name),
////            new OpPart((byte) 145, (byte) 145, union_name),
////            new OpPart((byte) 147, (byte) 147, mobile_name),
////            new OpPart((byte) 150, (byte) 152, mobile_name),
////            new OpPart((byte) 153, (byte) 153, telecom_name),
////            new OpPart((byte) 155, (byte) 156, union_name),
////            new OpPart((byte) 157, (byte) 159, mobile_name),
////            new OpPart((byte) 180, (byte) 180, telecom_name),
////            new OpPart((byte) 182, (byte) 183, mobile_name),
////            new OpPart((byte) 185, (byte) 186, union_name),
////            new OpPart((byte) 187, (byte) 188, mobile_name),
////            new OpPart((byte) 189, (byte) 189, telecom_name)
//     };

    // 国际冠码  如 0086  中国潍坊 00 + 86 + 536 *******  美国 011 + 1 +(区号)*********   美国境内之间的通话 1(区号)********

    //省和直辖市
    private static String provinces[] = new String[]{"山东", "江苏", "安徽", "湖北", "北京", "天津", "上海", "广东", "浙江", "广西", "甘肃", "吉林", "辽宁", "内蒙古", "新疆", "黑龙江", "河北", "重庆", "四川", "陕西", "福建", "海南", "江西", "山西", "湖南", "河南", "青海", "贵州", "宁夏", "云南", "西藏"};
    // 三大运营商
    private static String operations[] = { "移动", "联通", "电信" };

    private TelephonyManager mTelephonyManager ;
    private Context mContext;

    private String[] getcities(int province) {
        // int resouceId = mContext.getResources().getIdentifier("jiangsu", "array", mContext.getPackageName());
        String[] cities = mContext.getResources().getStringArray(R.array.shandong + province);
        return cities;
    }

    private PreferenceUtil mPrefUtil;
    private static PhoneNumberArea sInstance = null;

    public static PhoneNumberArea getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new PhoneNumberArea(context);
        }
        return sInstance;
    }

    private PhoneNumberArea(Context context) {
        mContext = context;
        mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        sISOCountryCode = mTelephonyManager.getNetworkCountryIso();
        if (StringUtil.isEmpty(sISOCountryCode)) {
            sISOCountryCode = mTelephonyManager.getSimCountryIso();
        }
        if (!StringUtil.isEmpty(sISOCountryCode)) {
            autoMatchCountry(sISOCountryCode);
        }

        mPrefUtil = PreferenceUtil.getInstance(mContext);
        mOpertatorName = mTelephonyManager.getSimOperatorName();
//        cities = getcities();
    }

    public String getNetworkOperatorName() {
        // 如果没有sim 卡拿到的是空
        if (StringUtil.isEmpty(mOpertatorName)) {
            mOpertatorName = mTelephonyManager.getNetworkOperatorName();
        }
        return mOpertatorName;
    }

    /*=========================================处理输入的号码=============================================
      /**
     * 大小写敏感的正规表达式批配
     *
     * @param source
     *            批配的源字符串
     *
     * @param regexp
     *            批配的正规表达式
     *
     * @return 如果源字符串符合要求返回真,否则返回假 如:  Regexp.isHardRegexpValidate("ygj@suncer.com.cn",email_regexp) 返回真
     */
    private Matcher isHardRegexpValidate(String source, String regexp)
    {
        Pattern p = Pattern.compile(regexp,Pattern.DOTALL);

        Matcher input = p.matcher(source);

        return input;
    }

    private  boolean checkRegex(String source, String regexp) {
        Pattern p = Pattern.compile(regexp,Pattern.CASE_INSENSITIVE);
        Matcher input = p.matcher(source);
        return input.find();
    }

    /**
     * 根据匹配的结果 替换成要替换的内容
     * @param matcher
     * @param replaceString
     */
    private String replace(Matcher matcher,String replaceString) {
        if(matcher!=null) {
            return matcher.replaceAll(replaceString);
        }else {
            return ""  ;
        }
    }


    /**
     * 暴露给外部的接口  处理所有输入的
     */
    public String replaceIpCall(String oldNumber) {

        String result = oldNumber;

        String regexDealExtraChars = "[*#\\-()\\.\\s]";
        Matcher matcher = isHardRegexpValidate(oldNumber, regexDealExtraChars);
        StringBuffer newNumber = new StringBuffer(result.replaceAll(regexDealExtraChars, ""));
        int newNumberLength = newNumber.length();

        // 这个位置要考虑
        //  86541234，，123


        if(checkRegex(newNumber.toString(),"^86.{8,}")) {
            if(newNumberLength > 11) {
                newNumber.reverse().append("+").reverse();
            }
        }


        if(checkRegex(newNumber.toString(),"^852.{7,}")) {
            if(newNumberLength > 10) {
                newNumber.reverse().append("+").reverse();
            }
        }

        if(checkRegex(newNumber.toString(),"^853.{7,}")) {
            if(newNumberLength > 11) {
                newNumber.reverse().append("+").reverse();
            }
        }

        if(checkRegex(newNumber.toString(),"^886.{7,}")) {
            if(newNumberLength > 11) {
                newNumber.reverse().append("+").reverse();
            }
        }

        result = newNumber.toString();

        String countryCode = mPrefUtil.get(PreferenceUtil.CONTACT_COUNTRY_CODE, String.class);
        String internationalCode = mPrefUtil.get(PreferenceUtil.CONTACT_INTERNATIONAL_PRFIX_CODE, String.class);
        if (0 == mPrefUtil.get(PreferenceUtil.SETTING_INIT, Integer.class)) {
            countryCode = sCountryCode;
            internationalCode = sInternationalCode;
        }

        StringBuilder internaitonCoadAndCountryCode = new StringBuilder(internationalCode);
        internaitonCoadAndCountryCode.append(countryCode);

        StringBuilder plusAndCountryCode = new StringBuilder("+");
        plusAndCountryCode.append(countryCode);

        StringBuilder plusCountryCodeZero  = new StringBuilder(plusAndCountryCode);
        plusCountryCodeZero.append("0");

        // 将“国际码+国家码”形式  替换成  “+国家码”
        if (!TextUtils.isEmpty(internaitonCoadAndCountryCode)
                && checkRegex(newNumber.toString(), "^" + internaitonCoadAndCountryCode.toString())) {
            matcher = isHardRegexpValidate(result, internaitonCoadAndCountryCode.toString());
            result = replace(matcher, plusAndCountryCode.toString());
        }

        // “+国家码+0“ 形式替换成 “+国家码”的形式
        if(checkRegex(result.toString(), "^\\"+plusCountryCodeZero.toString())) {
            matcher = isHardRegexpValidate(result,"^\\" + plusCountryCodeZero);
            result = replace(matcher,plusAndCountryCode.toString());
        }


        boolean isMobile = false;

        // 中国特别处理 当前用户所属地为中国
        if (countryCode.equals("86")) {

            // 当前的手机号为中国号码
            if (checkRegex(result, "^\\+861.*")) {
                // 中国手机号码
                if (!checkRegex(result, "^\\+8610.*")) {
                    isMobile = true;
                } else {
                    isMobile = false;
                }

            } else {
                isMobile = false;
            }

        }

        if(!isMobile) {
            matcher = isHardRegexpValidate(result, "^" + "\\" + plusAndCountryCode.toString() );
            result = replace(matcher, sCityPreCode);
        }

        if(countryCode.length() > 0) {

            String regex = "^\\" + plusAndCountryCode.toString();

            matcher = isHardRegexpValidate(result, regex);
            result = replace(matcher, "");
        }

        if(internationalCode.length() > 0 ){
            matcher = isHardRegexpValidate(result, "^\\+" );
            result = replace(matcher, internationalCode);
        } else {
            matcher = isHardRegexpValidate(result, "^\\+" );
            result = replace(matcher, "");
        }

        return result;

    }

    public static String formatPhoneNumDisplay(String oldNumber) {

        return oldNumber.replaceAll("-", "").replace(" ","");
    }

    /*=========================================处理输入的号码=============================================


    /**
     * 根据给出的号码前3位前缀 获取运营商的名称
     * @param opNumber
     * @return
     */
    private String GetOperation(int opNumber) {
//        int count = op_parts.length;
        int count = (mContext.getResources().getStringArray(R.array.op_parts)).length;
        String op_part[] = mContext.getResources().getStringArray(R.array.op_parts);
        int begin = 0,end = count-1;

        while(begin <= end) {
            int mid = (begin+end)/2;
            String opPartsCode = op_part[mid];
            String[] opPartsCodeArray = opPartsCode.split(",");
            int numberPrefix1 = Integer.parseInt(opPartsCodeArray[0]);
            int numberPrefix2 = Integer.parseInt(opPartsCodeArray[1]);
            int name_index = Integer.parseInt(opPartsCodeArray[2]);
            if(opNumber <= (numberPrefix2) && opNumber >= (numberPrefix1)) {
                return operations[name_index];
            }

            if(opNumber < (numberPrefix1)) {
                end = --mid;
            }else {
                begin = ++mid;
            }

        }

        return "";

    }

    /**
     *  根据对应的手机号前缀获取对应文件的二进制数据
     */
    private  byte[] LoadBytes(String name) {

        byte[] bytes = binFileBytes.get(name);

        if (bytes == null || bytes.length <= 0) {

            InputStream inputStream = null;

            try {

                inputStream = mContext.getAssets().open(name+".bin");
                byte[] buffer = new byte[inputStream.available()];
                int size = buffer.length;
                inputStream.read(buffer, 0, size);

                if(buffer.length > 0) {
                    binFileBytes.put(name, buffer);
                }

                return buffer;

            } catch (FileNotFoundException e) {
                // Auto-generated catch block

                //e.printStackTrace();
            } catch (IOException e) {
                // Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        // Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        }

        return bytes;
    }


    /**
     * 根据传入的手机号获取
     * @param phoneNumber
     * @return
     */
    private  byte[] LoadBytesForMobile(String phoneNumber) {

        if(phoneNumber.length() < 3) {
            return null;
        }

        String bytesFilePath = phoneNumber.substring(0,3);
        return LoadBytes(bytesFilePath);

    }

    /**
     * 根据字节数组数据中的索引 取出对应的归属地编号
     * @param bytes
     * @param index
     * @return
     */
    private  int area(byte[] bytes,int index) {

        if(bytes != null && bytes.length > 0  && index >= 0 ) {
            return (bytes[index] & 0xFF) + (bytes[index+1] & 0xFF)*256;
        }

        return -1;
    }

    /**
     * 获取省
     * @param bytes
     * @param index
     * @return
     */
    private  int province(byte[] bytes,int index) {

        if(bytes != null && bytes.length > 0  && index >= 0 ) {
            return (bytes[index+2] & 0xFF);
        }

        return -1;
    }

    /**
     * 获取地级市的信息
     * @param bytes
     * @param index
     * @return
     */
    private  int city(byte[] bytes,int index) {

        if(bytes != null && bytes.length > 0  && index >= 0 ) {
            return (bytes[index+3] & 0xFF);
        }

        return -1;
    }

    /**
     * 根据国内手机号 查询归属地
     * @param args
     */

    private  String GetAreaForMobile(String phoneNumber) {


        if (phoneNumber == null || phoneNumber.length() < 7) {
            return "";
        }

        byte[] binFileBytes = LoadBytesForMobile(phoneNumber);

        if (binFileBytes == null) {
            return null;
        }



        int subNumber =  Integer.parseInt(phoneNumber.substring(3,7));
//        int prefix = Integer.parseInt(phoneNumber.substring(0,3));

        StringBuilder result = new StringBuilder();
        int begin = 0, end = binFileBytes.length / 4 - 1;

        while (begin <= end) {

            int mid = (begin + end) / 2;
            int index = mid*4;

            if(subNumber >= area(binFileBytes,index) && (mid >= end || subNumber < area(binFileBytes,index+4))  ) {

                int provice = -1;
                int city = -1;
                if((provice = province(binFileBytes,index)) != -1) {
                    result.append(provinces[provice]);
                }

                if((city = city(binFileBytes,index)) != -1) {
                    if(provice != -1) {
                        result.append(getcities(provice)[city]);
                    }
                }
                //phone number area not include operation info
//                result.append(GetOperation(prefix));
                break;
            }

            if(subNumber > area(binFileBytes,index)) {
                begin = ++mid;
            }else {
                end= --mid;
            }

        }

        return result.toString();


    }

    /**
     * 根据国际区号获取国家名称
     * @param code
     * @return
     */
    private String GetNationalArea(String code) {
        code = StringUtil.filterUnNumber(code);
//        short codevalue = Short.parseShort(code);
        /*int count = national_codes.length;
        int begin = 0 ,end = count-1;

        while(begin <= end) {

           int mid = (begin+end)/2;

           if(codevalue == national_codes[mid].code) {
               return national_codes[mid].name;
           }

           if(codevalue > national_codes[mid].code) {
               begin = ++mid;
           }else {
               end = --mid;
           }

        }*/
        String[] national_codes = mContext.getResources().getStringArray(R.array.national_codes);
        int count = national_codes.length;
        int begin = 0 ,end = count-1;

        while(begin <= end) {
            int mid = (begin + end)/2;

            String nationCode = national_codes[mid];
            String[] nationCodeArray = nationCode.split(",");
            String codeItem = nationCodeArray[0];

            if(code.equals(codeItem)) {
                return nationCodeArray[1];
            }

            if(Integer.parseInt(code) > Integer.parseInt(codeItem)) {
                begin = ++mid;
            }else {
                end = --mid;
            }
        }

        return "" ;

    }

    /**
     * 根据国际区号获取国家名称
     * @param code
     * @return
     */
    private String getNationalAreaNew(String code) {
        String[] national_codes = mContext.getResources().getStringArray(R.array.national_codes);
        int count = national_codes.length;
        int begin = 0 ,end = count-1;

        while(begin <= end) {
            int mid = (begin + end)/2;

            String nationCode = national_codes[mid];
            String[] nationCodeArray = nationCode.split(",");
            String codeItem = nationCodeArray[0];

            if(code.equals(codeItem)) {
                return nationCodeArray[1];
            }

            if(Integer.parseInt(code) > Integer.parseInt(codeItem)) {
                begin = ++mid;
            }else {
                end = --mid;
            }
        }

        return "" ;

    }

    /**
     * 根据固话区号定位地级市信息
     * @param code
     * @return
     */
    private  String _GetAreaForTelephone(String code) {


        if (code == null || code.length() < 2) {
            return "";
        }

        byte[] binFileBytes = LoadBytes("areacode");

        if (binFileBytes == null) {
            return null;
        }


        int codeValue = Integer.valueOf(code);
        StringBuilder result = new StringBuilder();
        int begin = 0, end = binFileBytes.length / 4 - 1;

        while(begin <= end) {

            int mid = (begin + end) / 2;
            int index = mid * 4;

            if(codeValue == area(binFileBytes,index)  ) {

                int provice = -1;
                int city = -1;
                if((provice = province(binFileBytes,index)) != -1) {
                    result.append(provinces[provice]);
                }

                if((city = city(binFileBytes,index)) != -1) {
                    if(provice != -1) {
                        result.append(getcities(provice)[city]);
                    }
                }

                return result.toString();


            }

            if(codeValue > area(binFileBytes,index)) {
                begin = ++mid;
            }else {
                end= --mid;
            }


        }

        return "";


    }

    /**
     *  查寻固定电话归属地
     * @param phoneNumber
     * @return
     */
    private  String GetAreaForTelephone(String phoneNumber)  {

        if(phoneNumber.length() < 4) {
            return "";
        }

        String result = _GetAreaForTelephone(phoneNumber.substring(0,3));
        if(result ==null || result.length() ==0) {
            result =  _GetAreaForTelephone(phoneNumber.substring(0,4));
        }

        return result;


    }

    /**
     * 返回本地号码归属地识别信息   识别出是本地号码后用的方法
     * @param phoneNumber
     * @return
     */
    private  String retLocalArea(String phoneNumber) {
        // noly use to report error.
        String rawPhoneNum = phoneNumber;

        String result;
        if (StringUtil.isEmpty(phoneNumber)) {
            return null;
        }
        phoneNumber = this.replaceIpCall(phoneNumber);
        phoneNumber = StringUtil.filterUnNumber(phoneNumber);

        if (TextUtils.isEmpty(phoneNumber)) {
            // MobclickAgent.reportError(mContext, "PhoneNumberArea.retLocalArea(String)\nrawPhoneNum: " + rawPhoneNum);
            return null;
        }
        // 北京固话判断
        if(phoneNumber.substring(0,1).equals("0")) {
            result =  GetAreaForTelephone(phoneNumber);
        }else {
            result = GetAreaForMobile(phoneNumber);
        }

        return result;

    }

    /**
     * 主体逻辑 提供给外部程序直接调用的接口
     * @param phoneNumber
     * @return
     */
    public String getArea(String phoneNumber, boolean needOp) {

        // extension number
        if (phoneNumber.contains(",,")) {
            int split = phoneNumber.indexOf(",,");
            phoneNumber = phoneNumber.substring(0, split);
        }

        phoneNumber = phoneNumber.replaceAll(StringUtil.SAPCE_REGEX, "");
        String countryCode = mPrefUtil.getString(
                PreferenceUtil.CONTACT_COUNTRY_CODE, "86");
        String internationalCode = mPrefUtil.getString(
                PreferenceUtil.CONTACT_INTERNATIONAL_PRFIX_CODE, "00");

        String result = "";
        if (phoneNumber.startsWith("+86")) {
            String sTmp = phoneNumber.substring("+86".length());
            result = retLocalArea(sTmp);
        } else {
            phoneNumber = replaceIpCall(phoneNumber);
        }

        if (phoneNumber == null || phoneNumber.length() < 4) {
            return "";
        }

        String pre = internationalCode + "86";
        if (phoneNumber.startsWith(pre)) {
            String sTmp = phoneNumber.substring(pre.length());
            result = retLocalArea(sTmp);
        } else {
            // 中国本地的号码 处理
            if (countryCode.equals("86") && !phoneNumber.startsWith(internationalCode)) {
                result = retLocalArea(phoneNumber);
            } else if (phoneNumber.startsWith("+86")) {
                result = retLocalArea(phoneNumber.substring("+86".length()));
            }
        }

        int il = internationalCode.length();

        if (result == null || result.length() == 0) {
            // 处理00852 带 国际号码+国家码（非中国）的 情况处理
            if (phoneNumber.length() > il) {

                int pl = phoneNumber.length();

                String tmp = phoneNumber.substring(0, il);
                boolean judge = tmp.equals(internationalCode);

                if (judge) {
                    String sTmp = phoneNumber.substring(il);
                    for (int i = 4; i > 0; i--) {
                        if ((i + il) > pl) {
                            continue;
                        }

                        result = GetNationalArea(sTmp.substring(0, i));
                        if (result != null && result.length() > 0) {
                            break;
                        }
                    }
                }
            }
        }

        if (result == null || result.length() == 0) {
            return "本地电话";
        }
        String op = null;
        if (needOp) {
            phoneNumber = StringUtil.filterUnNumber(phoneNumber);
            int prefix = Integer.parseInt(phoneNumber.substring(0,3));
            op = GetOperation(prefix);
        }
        if (!StringUtil.isEmpty(op)) {
            result += op;
        }
        return result;

    }

    public String getAreaNew(String phoneNumber) {
        StringBuilder sb = filterPhoneNum(phoneNumber);

        String countryCode = mPrefUtil.getString(
                PreferenceUtil.CONTACT_COUNTRY_CODE, "86");
        if ("86".equals(countryCode)) {
            String s = sb.toString();
            if (s.startsWith("+86")) {
                s = s.substring(3);
            } else if (s.startsWith("17951") || s.startsWith("12593")
                    || s.startsWith("17911") || s.startsWith("17901")) {
                s = s.substring(5);
                // international code
                if (s.startsWith("00")) {
                    String code = matchCode(mContext, s.substring(2));
                    if (code == null || code.length() == 0) {
                        return "";
                    } else {
                        return getNationalAreaNew(code);
                    }
                }
            } else if (s.startsWith("+")) {
                // international code
                String code = matchCode(mContext, s.substring(1));
                if (code == null || code.length() == 0) {
                    return "";
                } else {
                    return getNationalAreaNew(code);
                }
            } else if (s.startsWith("00")) {
                // international code
                if (s.startsWith("00")) {
                    String code = matchCode(mContext, s.substring(2));
                    if (code == null || code.length() == 0) {
                        return "";
                    } else {
                        return getNationalAreaNew(code);
                    }
                }
            }

            if (s.length() < 3) {
                return "本地电话";
            }

            String ret = null;
            if (s.substring(0, 1).equals("0")) {
                ret = GetAreaForTelephone(s);
            } else {
                ret = GetAreaForMobile(s);
            }
            return ret;
        } else {
            return getArea(phoneNumber, false);
        }
    }

    private StringBuilder filterPhoneNum(String phoneNumber) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < phoneNumber.length(); i++) {
            char c = phoneNumber.charAt(i);
            if (PhoneNumberUtils.isISODigit(c) || c == '+') {
                sb.append(c);
            }
        }
        return sb;
    }

    private void autoMatchCountry(String isoCountryCode) {
        String[] national_codes = mContext.getResources().getStringArray(R.array.national_codes);
        int begin = 0,end = national_codes.length-1;
        if (isoCountryCode.equalsIgnoreCase("cn")) {
            //86,中国,CN,0,00
            return;
        }
        while(begin <= end) {
            String nationCode = national_codes[begin];
            String[] nationCodeArray = nationCode.split(",");
            if(nationCodeArray[2].equalsIgnoreCase(isoCountryCode)) {
                sISOCountryCode = isoCountryCode;
                sCountryCode = nationCodeArray[0];
                sInternationalCode = nationCodeArray[4];
                sCityPreCode = nationCodeArray[3];
                sCountryName = nationCodeArray[1];
                break;
            }
            begin++;

        }
    }

    //: to fix this matcher
    public static String stripShortNumber(String source) {

        if (null == source) {
            Log.w(TAG, "source == null!");
        }

        String s = source;
        if (s.startsWith("+86") || s.startsWith("852")
                || s.startsWith("853") || s.startsWith("886")
                || s.startsWith("86 ")) {
            return s.substring(3);
        } else if (s.startsWith("17951") || s.startsWith("12593")
                || s.startsWith("17911") || s.startsWith("17901")) {
            return s.substring(5);
        }

        return s;
    }

    /**
     * 判断是否为手机号 主要针对中国
     *
     * @param phoneNumber
     * @author gaotong
     * @return
     */
    public boolean isMobilePhone(String phoneNumber, int label) {
        if (label == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
            return true;
        }

        boolean result = false;
        phoneNumber = phoneNumber.replaceAll("\\(", "");
        phoneNumber = phoneNumber.replaceAll("\\)", "");
        phoneNumber = phoneNumber.replaceAll("\\-", "");
        phoneNumber = phoneNumber.replaceAll(" ", "");
        String countryCode = mPrefUtil.getString(
                PreferenceUtil.CONTACT_COUNTRY_CODE, "86");
        if ("86".equals(countryCode)) {
            return StringUtil.isMobilePhoneInChina(phoneNumber);
        } else {
            result = false;
        }
        return result;
    }

    /**
     * 号码对比
     * @param number1
     * @param number2
     * @return
     */
    public boolean compareNumber(String number1,String number2) {

        boolean result = false;
        boolean isNumber1Mobile = false;
        boolean isNumber2Mobile = false;

        // 做处理之后 临时变量
        String sNumber1 = "";
        String sNumber2 = "";

        //   判断是否为手机号
        if(!TextUtils.isEmpty(number1)) {
            isNumber1Mobile = true;// isMobilePhone(number1, );
        }

        //   判断是否为手机号
        if(!TextUtils.isEmpty(number2)) {
            isNumber2Mobile = true;// isMobilePhone(number2);
        }

        if(isNumber1Mobile && isNumber2Mobile) {

            //  做特殊化处理  把前缀都去掉   如: 86  +86
            sNumber1 = replaceIpCall(number1);
            sNumber2 = replaceIpCall(number2);
            if(sNumber1.equals(sNumber2)) {
                result = true;
            }

        }else if(!isNumber1Mobile && !isNumber2Mobile){
            //  做特殊化处理  把前缀都去掉   如: 86  +86
            sNumber1 = replaceIpCall(number1);
            sNumber2 = replaceIpCall(number2);
            if(sNumber1.equals(sNumber2)) {
                result = true;
            }

        }else {
            result = false;
        }

        return result;

    }

//    /**
//     * 判断是否存在于黑白名单中
//     * @param number
//     * @return    -1 表示不存在  0 表示再黑名单中  1 表示再白名单中
//     */
//    public int judgeIsExistInBlackWhilteList(String number) {
//        int result =-1;
//
//        // 存在于黑白名单中所有号码
//        List<NumberType> wkPhones = ContactsDBReader.selectCommunicationRuleAllPhones(mContext
//                .getContentResolver());
//
//        if (wkPhones != null && wkPhones.size() > 0) {
//            for (NumberType NumberType : wkPhones) {
//                if (compareNumber(number, NumberType.phone)) {
//                    result = NumberType.type;
//                    break;
//                }
//            }
//        }
//
//        return result;
//
//    }

    private static String[] mccmnc = {"46000","46001","46002","46003","46005","46006","46007" };
    private static String[] ipcode = {"17951","17911", "17901"};
    public static Map<String,operator>  mccmncMap = new HashMap<String, operator>();
    public static enum operator {ChinaMobile,ChinaUnicom, ChinaTelecom};

    static {
        mccmncMap.put(mccmnc[0], operator.ChinaMobile); //46000
        mccmncMap.put(mccmnc[1], operator.ChinaUnicom); //46001
        mccmncMap.put(mccmnc[2], operator.ChinaMobile); //46002
        mccmncMap.put(mccmnc[3], operator.ChinaTelecom); //46003
        mccmncMap.put(mccmnc[4], operator.ChinaTelecom);  //46005
        mccmncMap.put(mccmnc[5], operator.ChinaUnicom);  //46006
        mccmncMap.put(mccmnc[6], operator.ChinaMobile);  //46007
    }

    public String getIpcallNum(String ipcodeS) {

        if (!TextUtils.isEmpty(ipcodeS)) {
            return ipcodeS;
        }

        if (mTelephonyManager != null) {
            String mccmnc = mTelephonyManager.getSimOperator();
            if (!TextUtils.isEmpty(mccmnc)) {
                operator soperators = mccmncMap.get(mccmnc);
                if (soperators != null) {
                    switch (soperators) {
                        case ChinaMobile:
                            return ipcode[0];
                        case ChinaUnicom:
                            return ipcode[1];
                        case ChinaTelecom:
                            return ipcode[2];
                        default:
                            break;
                    }
                }
            }
        }

        return "";
    }

    public static boolean isPhoneNumDigit (char c) {
        return c >= '0' && c <= '9' || c == '+';
    }


    public static String formatNum(Context c, String rawNum) {

        if (rawNum == null || rawNum.length() == 0) {
            return "";
        }

        char[] charArr = rawNum.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < charArr.length; i++) {
            if (isPhoneNumDigit(charArr[i])) {
                sb.append(charArr[i]);
            }
        }

        String s = sb.toString();
        if (s.length() < 3) return "";

        if (s.charAt(0) == '+') {
            // to see if international phone number
            String nCode = matchCode(c, s.substring(1));
            if (!"".equals(nCode)) {
                String phoneNum = s.substring(nCode.length() + 1);
                return nCode + " " + phoneNum;
            } else {
                return "";
            }
        } else if (s.startsWith("00")) {
            // to see if international phone number
            String nCode = matchCode(c, s.substring(2));
            if (!"".equals(nCode)) {
                String phoneNum = s.substring(nCode.length() + 2);
                return nCode + " " + phoneNum;
            } else {
                return "";
            }
        } else {
            // chinese phone number
            if (sb.length() < 11) {
                return "";
            }

            String num = sb.substring(sb.length() - 11);
            if (num.startsWith("13") || num.startsWith("14")
                    || num.startsWith("15") || num.startsWith("18")) {
                // TODO 不加86
                //return "86 " + num;
                return num;
            } else {
                return "";
            }
        }
    }

    private static String matchCode(Context c, String phoneNum) {
        String[] codeOne = c.getResources().getStringArray(R.array.national_code_one);
        for (String code : codeOne) {
            if(phoneNum.startsWith(code)) {
                return code;
            }
        }

        String[] codeTwo = c.getResources().getStringArray(R.array.national_code_two);
        for (String code : codeTwo) {
            if (phoneNum.startsWith(code)) {
                return code;
            }
        }

        String[] codeThree = c.getResources().getStringArray(R.array.national_code_three);
        for (String code : codeThree) {
            if (phoneNum.startsWith(code)) {
                return code;
            }
        }

        return "";
    }


    //判断email格式是否正确
    public static  boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

}
